package com.webdrop.gui;

import java.util.List;
import java.util.Vector;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONException;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.storage.client.Storage;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.webdrop.client.HttpRequest;
import com.webdrop.client.UrlToServer;

public class ReadFiles extends Composite{

	FlowPanel grid;
	String googleId;
	String sessionId;
	Storage sessionStorage;
	List<String> allFileName;
	Event event;

	UrlToServer urlToServer = new UrlToServer();

	public ReadFiles(){
		grid=new FlowPanel();
		grid.addStyleName("imgPanel");
		allFileName =new Vector<String>();
		initWidget(grid);
	}


	protected void onLoad() 
	{
		super.onLoad();
		grid.clear();

		sessionStorage = Storage.getSessionStorageIfSupported();
		if( sessionStorage != null ){
			googleId = sessionStorage.getItem("googleId");
			sessionId = sessionStorage.getItem("sessionId");
			getData();
		}

	}


	protected void onUnload() 
	{
		super.onUnload();
		grid.clear();
	}


	public void reloadGrid(){
		onLoad();
	}


	/**
	 * Gets the thumbimages as a json
	 */
	public void getData(){
		new HttpRequest(urlToServer.getUrlToServer()+"getThumbsJson.php?googleId="+googleId+"&sessionId="+sessionId) {
			@Override
			public void onResponseReceived(Request request, Response response) {
				if (200 == response.getStatusCode())
				{			
					try {
						JSONValue jsonValue = JSONParser.parseStrict(response.getText());
						JSONArray jsonArray = jsonValue.isArray();
						if (jsonArray != null) {
							addThumbs(jsonArray);
						}
					} catch (JSONException  e) {
						displayError("Could not parse JSON");
					}
				}
				else{
					displayError("Couldn't retrieve JSON (" + response.getStatusText() + ")");
				}
			}
		};
	}


	public void addThumbs(JSONArray array){
		JSONValue jsonValue;
		for (int i=0; i<array.size(); i++) {
			JSONObject jsStock;
			JSONString jsSymbol;
			//			    JSONNumber jsPrice, jsChange;

			if ((jsStock = array.get(i).isObject()) == null) continue;

			if ((jsonValue = jsStock.get("imageName")) == null) continue;
			if ((jsSymbol = jsonValue.isString()) == null) continue;


			//remove " fnutts
			final String thumbPath = jsSymbol.toString().replaceAll("\"", "");
			final String thumbName;

			thumbName = thumbPath.substring(thumbPath.lastIndexOf("/")+1, thumbPath.length());
			allFileName.add(thumbName);
			//			

			final Image thumbImage = new Image();

			new HttpRequest(urlToServer.getUrlToServer()+"getThumbImage.php?googleId="+googleId+"&sessionId="+sessionId+"&thumbName="+thumbName) {
				@Override
				public void onResponseReceived(Request request, Response response) {
					if (200 == response.getStatusCode())
					{			
						try {
							String result = response.getText();
							thumbImage.setUrl(result);

						} catch (JSONException  e) {
							displayError("Could not parse JSON");
						}
					}
					else{
						displayError("Couldn't retrieve JSON (" + response.getStatusText() + ")");
					}
				}
			};


			thumbImage.setTitle(thumbName);

			thumbImage.addClickHandler(new ClickHandler() {

				public void onClick(ClickEvent event) {

					popUpImg(thumbName);
				}
			});

			thumbImage.addStyleName("tmpImg");
			grid.add(thumbImage);

		}
	}

	/**
	 *  popup that shows an error
	 * @param error
	 */
	public void displayError(String error){
		PopupPanel popUp = new PopupPanel();
		popUp.show();
		Label errorMLabel = new Label(error);
		popUp.setPopupPosition(500,100);

		popUp.setHeight("100px");
		popUp.setAutoHideEnabled(true);
		popUp.add(errorMLabel);
	}

	/**
	 * The gallery function
	 * @param name
	 */
	public void popUpImg( String name){
		VerticalPanel popUpPanel = new VerticalPanel();
		VerticalPanel nextImgPanel = new VerticalPanel();
		HorizontalPanel buttonPanel = new HorizontalPanel();

		final DialogBox popUp = new DialogBox();
		final Button close = new Button("Close");
		final Button previousImage = new Button("Previous Image");
		final Button nextImage = new Button("Next Image");

		buttonPanel.addStyleName("buttonpopup");
		close.addStyleName("closeimgbutton");
		nextImgPanel.setStyleName("nextimgpanel");
		nextImgPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
		buttonPanel.add(previousImage);
		buttonPanel.add(close);
		nextImgPanel.add(nextImage);
		buttonPanel.add(nextImgPanel);
		popUp.setTitle(name);
		popUp.show();
		final int nextIndex=allFileName.indexOf(name)+1;
		final int prevIndex=allFileName.indexOf(name)-1;
		popUp.setPopupPosition((Window.getClientWidth()/2)-200,60);
		popUp.addStyleName("popUpSize");
		popUp.setWidth("400px");
		popUp.setAutoHideEnabled(false);
		final Image popUpImg = new Image();


		// Get the gallery images
		new HttpRequest(urlToServer.getUrlToServer()+"getGalleryImage.php?googleId="+googleId+"&sessionId="+sessionId+"&imageName="+name) {
			@Override
			public void onResponseReceived(Request request, Response response) {
				if (200 == response.getStatusCode())
				{			
					try {
						String result = response.getText();
						popUpImg.setUrl(result);

						close.addClickHandler(new ClickHandler() {

							@Override
							public void onClick(ClickEvent event) {
								popUp.clear();
								popUp.hide();
							}
						});

						nextImage.addClickHandler(new ClickHandler() {

							@Override
							public void onClick(ClickEvent event) {
								if(nextIndex==allFileName.size()){
									//									nextImage.setVisible(false);
								}
								else{
									popUp.clear();
									popUp.hide();
									popUpImg(allFileName.get(nextIndex));

								}
							}
						});

						previousImage.addClickHandler(new ClickHandler() {

							@Override
							public void onClick(ClickEvent event) {
								// 
								if(prevIndex==-1){
									//									previousImage.setVisible(false);
								}
								else{
									if(previousImage.isVisible()){
										popUp.clear();
										popUp.hide();
										popUpImg(allFileName.get(prevIndex));

									}
								}
							}

						});
					}
					catch (JSONException  e) {
						displayError("Could not create Image");
					}
				}
				else{
					displayError("Couldn't retrieve Image (" + response.getStatusText() + ")");
				}
			}
		};
		popUpPanel.add(buttonPanel);
		popUpPanel.add(popUpImg);

		popUp.add(popUpPanel);
	}

}


